package com.inspur.gs.sbssdl.dzyhpgl.dzyhyu.dzyhyu.front.sbssdzyhptz.voactions;
import com.inspur.edp.bff.api.manager.context.QueryContext;
import com.inspur.edp.bff.spi.action.query.AbstractQueryAction;
import com.inspur.edp.caf.db.dbaccess.DbParameter;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.caf.db.dbaccess.IConverToListFunc;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.dependenceTemp.Pagination;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IValuesContainer;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import static com.inspur.edp.qdp.bql.execute.BqlExecuterUtil.getBqlExecuter;


public class queryDataVOAction extends AbstractQueryAction {
	// select
	private final String SELECT = "select wlMc as yhpmc ,org.NAME_CHS as gkbm ,sum(tsl) as sl ";
	// from
	private final String FROM = " from SBSS_DZYHP_item it\n" +
			"left join GSpUser usr on usr.id = it.SYRYID\n" +
			"left join gspsysorg org on org.id = it.GKBMID ";

	// group by
	private String GROUPBY = " group by wlMc, org.NAME_CHS ";

	// where
	private String WHERE = " where 1=1";
	// params
	private final List<IDbParameter> params = new ArrayList<>();

	private final IBqlExecuter bqlExecuter = getBqlExecuter();

	public queryDataVOAction(QueryContext context){
		super(context);
	}
	@Override
	public void execute() {
		// 获取页面表单的筛选项目
		EntityFilter filter = getQueryContext().getFilter();
		Pagination pageInfo = filter.getPagination();
		ArrayList<FilterCondition> filters = filter.getFilterConditions();

		// 查询数据
		ArrayList<IEntityData> rows = queryData(filters, pageInfo);
		// 查询数据总数
		Integer count = queryCount();
		pageInfo.setPageCount(rows.size());
		pageInfo.setTotalCount(count);

		// 通用的直接拷贝，将结果传递给下一个执行器
		HashMap<String, ArrayList<IEntityData>> queryresult = new HashMap<>();
		queryresult.put("queryresult", rows);
		getQueryContext().setQueryResult(rows);
		setResult(queryresult);

	}


	private ArrayList<IEntityData> queryData(ArrayList<FilterCondition> filters, Pagination pagination){
		StringBuilder sql = new StringBuilder(SELECT + FROM);
		for (FilterCondition f : filters) {

			if (f.getFilterField().equals("gkbm") && !f.getValue().isEmpty()) {
				WHERE += " and it.GKBMID = :gkbm ";
				params.add(new DbParameter("gkbm", f.getValue()));
			}

			if (f.getFilterField().equals("yhpmc") && !f.getValue().isEmpty()) {
				WHERE += " and wlMc like :yhpmc ";
				params.add(new DbParameter("yhpmc", "%"+f.getValue()+"%"));
			}

		}
		bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
		List<IEntityData> data = bqlExecuter.executeSelectStatement(appendPagination(sql, pagination),new ArrayList<>(), new myIconver(), params.toArray(new IDbParameter[]{}));
		return new ArrayList<>(data);
	}


	private String appendPagination(StringBuilder sql, Pagination pagination) {
		if (pagination == null) {
			pagination = new Pagination(20, 1);
		}
		int offset = pagination.getPageSize() * (pagination.getPageIndex() - 1);
		sql.append(WHERE)
				.append(GROUPBY)
				.append(" offset ")
				.append(offset)
				.append(" rows FETCH NEXT ")
				.append(pagination.getPageSize())
				.append(" ROWS ONLY");
		return sql.toString();
	}

	private Integer queryCount() {
		String sql = "select count(*) count from ( " + SELECT + FROM + WHERE + GROUPBY + ")";
		bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
		List<DynamicResultRow> rows = bqlExecuter.executeSelectStatement(sql,new ArrayList<>(), params.toArray(new IDbParameter[]{}));
		for (DynamicResultRow row : rows) {
			if (row.get("count") != null) {
				return Integer.valueOf(row.get("count").toString());
			}
		}
		return 0;
	}


	private class myIconver implements IConverToListFunc<IEntityData> {
		private IEntityData vo;

		@Override
		public List<IEntityData> convert(List<DynamicResultRow> list) {
			// 将Vo中所有的字段都填入到这里
			ArrayList<IEntityData> entityData = new ArrayList<>();
			for (DynamicResultRow row : list) {
				vo = getContext().createData();
				for (String s : vo.getPropertyNames()) {
					if (vo.getValue(s) instanceof IValuesContainer) {

					} else {
						vo.setValue(s, row.get(s));
					}
				}
				vo.setID(UUID.randomUUID().toString());
				entityData.add(vo);
			}
			return entityData;
		}

		private void setValue(DynamicResultRow row, String propertyName, String... vars) {
			((IValuesContainer) vo.getValue(propertyName)).setValue(propertyName, row.get(propertyName));
			for (String var : vars) {
				if (var != null) {
					String value = propertyName + "_" + var;
					((IValuesContainer) vo.getValue(propertyName)).setValue(value, row.get(value));
				}
			}
		}
	}
}
